package com.derbysoft.dswitch.adapter.ihg.common.service;

import com.derbysoft.dswitch.adapter.ihg.common.utils.Constants;
import org.apache.commons.lang.StringUtils;

import java.util.LinkedHashSet;
import java.util.Set;

/**
 * User: jason
 * Date: 2013-01-05
 */

public class PriorityMarcher {
    private Set<PriorityField> matchFields = new LinkedHashSet<PriorityField>();

    public PriorityMarcher(String priority) {
        if (StringUtils.isBlank(priority)) {
            return;
        }
        for (String field : StringUtils.split(priority, Constants.AMPERSAND)) {
            if (containsField(StringUtils.trim(field))) {
                matchFields.add(PriorityField.valueOf(StringUtils.upperCase(StringUtils.trim(field))));
            }
        }
    }

    public String matchChannel(String channel) {
        if (needMatch(PriorityField.CHANNEL)) {
            return channel;
        }
        return Constants.ASTERISK;
    }

    public String matchHotel(String hotel) {
        if (needMatch(PriorityField.HOTEL)) {
            return hotel;
        }
        return Constants.ASTERISK;
    }

    public String matchRatePlan(String ratePlan) {
        if (needMatch(PriorityField.RATE_PLAN)) {
            return ratePlan;
        }
        return Constants.ASTERISK;
    }

    public String matchRoomType(String roomType) {
        if (needMatch(PriorityField.ROOM_TYPE)) {
            return roomType;
        }
        return Constants.ASTERISK;
    }

    private boolean needMatch(PriorityField field) {
        return matchFields.contains(field);
    }

    private static boolean containsField(String field) {
        for (PriorityField priorityField : PriorityField.values()) {
            if (priorityField.name().equals(StringUtils.upperCase(field))) {
                return true;
            }
        }
        return false;
    }

    @Override
    public String toString() {
        StringBuilder builder = new StringBuilder();
        for (PriorityField needMatchField : matchFields) {
            builder.append(needMatchField).append(Constants.SEMICOLON);
        }
        return StringUtils.removeEnd(builder.toString(), Constants.SEMICOLON);
    }
}
